"""
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
* Neither the names of the authers, nor the names of its contributors, may be used to endorse or 
promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS/COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
REGENTS/COPYRIGHT OWNERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

@Author Fredrique Samuels <fredriquesamuels@gmail.com>
@network.py  
"""

import socket
import urllib
import sgmllib
import smtplib
import string
import urllib2
import os
import time
import shutil

def getHTML(url):
    filehandle = urllib.urlopen(url)
    html = filehandle.read()
    return html

def saveHTML(url,file_):
    html = getHTML(url)
    fh = open(file_,'w')
    fh.write(html)
    fh.close()
    
def getImage(url):
    opener1 = urllib2.build_opener()
    page1 = opener1.open(url)
    my_picture = page1.read()
    return my_picture

def getImageFromWeb(link,save):
    img  = getImage(link)
    fh = open(save,'wb')
    fh.write(img)
    fh.close()

class TXP:
    def __init__(self,timeout = 0):
        self._CONN_TYPE = -1
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._timeOut = timeout
        self._socket.settimeout(self._timeOut)
        self.conn = []

    def bind(self,host = '',port = 50007):
        self._socket.bind((host, port))
        
    def listen(self,max_conn = 100):
        self._socket.listen(max_conn)
        self._socket.settimeout(self._timeOut)
        conn = None
        addr = None
        try:
            conn,addr = self._socket.accept()
        except:
            return conn,addr

        self._CONN_TYPE = 0
        return conn,addr

    def connect(self,host = '127.0.0.1',port = 50007):
        if self._timeOut == 0:
            self._socket.settimeout(5)
        try:
            self._socket.connect((host,port))
        except Exception , e:
            return False
        self._socket.settimeout(self._timeOut)
        self._CONN_TYPE = 1
        return True

    def setTimeOut(self,t):
        self._timeOut = t
        
    def close(self):
        self._socket.close()

    def get_socket(self):
        return self._socket

    def recv(self,size = 1024):
        if self._timeOut == 0:
            self._socket.settimeout(5)
        if self._CONN_TYPE == 1:
            return  self._socket.recv(size)
        elif self._CONN_TYPE == 0:
            return self._r_conn.recv(size)
        

    def send(self,data,conn = None):
        if self._CONN_TYPE == 1:
            return  self._socket.send(data)
        elif self._CONN_TYPE == 0:
            return conn.send(data)

    def closeConnection(self,conn):
        self.conn.remove(conn)
        conn.close()
        
def ser():
    s = TXP(1)
    s.bind()
    conns = []
    while 1:
        conn,addr = s.listen()
        if not conn is None:
            print conn
            conns.append(conn)
            to_remove = []
            for c in conns:
                try:
                    s.send("Hello",c)
                except:
                    to_remove.append(c)
            for c in to_remove:
                conns.remove(c)
                    
        

def cl():
    
    while 1:
        s = TXP()
        if s.connect():
            print s.recv()
            s.close()
        time.sleep(2)

def main():
    #thread.start_new_thread(ser,())
    #ime.sleep(2)
    thread.start_new_thread(cl,())
    time.sleep(10)
    

if __name__ == '__main__':
    main()
